package scheduler

import (
	"awesome-devops/applications/nodes"
	"awesome-devops/applications/rpc/client"
	"awesome-devops/applications/rpc/define"
	"context"
	"errors"
)

var scheduler Scheduler

type Scheduler struct {
}

func (scheduler *Scheduler) Run(deployId int) (error, interface{}) {
	err, runners := nodes.GetNodeManager().GetRunner(deployId)
	if err != nil {
		return err, nil
	}
	if len(runners) == 0 {
		return errors.New("找不到可用的调度节点,请检查节点项目配置与标签"), nil
	}
	runner := runners[0]
	rpcClient := client.GetRpcClient(runner.Runner.Ip, runner.Runner.RpcPort)
	service, err := rpcClient.GetRunnerService()
	if err != nil {
		return err, nil
	}
	task, err := service.RunDeployTask(context.Background(), &define.RunnerRequest{
		Id: int32(deployId),
	})
	if err != nil {
		return err, nil
	}
	return nil, task
}

func InitScheduler() {
	scheduler = Scheduler{}
}

func GetScheduler() *Scheduler {
	return &scheduler
}
